package cn.virens.service.impl.base.upload;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.io.FileUtil;
import cn.virens.CacheKeys;
import cn.virens.database.common.BaseServiceImpl;
import cn.virens.database.common.mapper.ExampleWrapper;
import cn.virens.database.mysql.mapper.base.BaseUploadFileMapper;
import cn.virens.database.mysql.model.base.BaseUploadFile;
import cn.virens.exception.APIException;
import cn.virens.service.inter.base.upload.BaseUploadFileService;

/**
 * 文件管理 - base_upload_file
 *
 * @author Virens
 * @since  2018-08-25 11:04:10
 */
@Service
public class BaseUploadFileServiceImpl extends BaseServiceImpl<BaseUploadFileMapper, BaseUploadFile> implements BaseUploadFileService {

	public BaseUploadFileServiceImpl() {
		super(BaseUploadFile.class);
	}

	@Override
	public List<? extends BaseUploadFile> selectAll(Map<String, Object> param) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.and().andLike("code", criteriaLike(param, "code"));
		example.and().andLike("name", criteriaLike(param, "name"));

		return mBaseMapper.selectByExample(example);
	}

	@Override
	@Transactional(readOnly = true)
	@Cacheable(value = CacheKeys.UPLOAD_FILE, key = "#p0", unless = "#result == null")
	public BaseUploadFile selectOne(Serializable code) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.and().andEqualTo("code", code);

		return mBaseMapper.selectOne(example);
	}

	@Override
	@Transactional(readOnly = false)
	@CacheEvict(value = CacheKeys.UPLOAD_FILE, key = "#p0")
	public int delete(String rootPath, String... codes) {
		ExampleWrapper example = ExampleWrapper.of(clazz);
		example.and().andIn("code", Arrays.asList(codes));

		// 删除物理文件
		List<BaseUploadFile> temp = mBaseMapper.selectByExample(example);
		for (BaseUploadFile baseUploadFile : temp) {
			FileUtil.del(baseUploadFile.getPath(rootPath));
		}

		// 删除数据库文件
		return mBaseMapper.deleteByExample(example);
	}

	@Override
	public int delete(Serializable... id) {
		throw new APIException("DISABLE_API", "Disable create the resource!");
	}

	@Override
	public BaseUploadFile update(BaseUploadFile record) {
		throw new APIException("DISABLE_API", "Disable create the resource!");
	}
}
